import { defineStore } from "pinia";
import { ref } from "vue";
import { RouteRecordRaw } from "vue-router";
import { store } from "@/store";
import { getInitMenus } from "@/api/user";
import { constantRoutes } from "@/router";
import type { IPermissionItem } from "@/api/user/types";

const Layout = () => import("@/layout/index.vue");
const modules = import.meta.glob("../../views/**/**.vue");

function filterAsyncRoutes(pList: IPermissionItem[]) {
  const asyncRoutes: RouteRecordRaw[] = [];
  pList.forEach((pItem) => {
    // 菜单
    if (pItem.type === 1) {
      let tempRoute = {
        ...pItem,
      };

      if (!tempRoute.name) {
        tempRoute.name = pItem.path;
      }

      // 顶级路由
      if (pItem.pid === "0") {
        tempRoute.component = Layout;
      } else {
        const component = modules[`../../views/${tempRoute.component}.vue`];
        if (component) {
          tempRoute.component = component;
        } else {
          tempRoute.component = modules[`../../views/error-page/404.vue`];
        }
      }
      if (pItem.children && pItem.children.length > 0) {
        tempRoute.children = filterAsyncRoutes(pItem.children);
      }
      asyncRoutes.push(tempRoute);
    }
  });
  return asyncRoutes;
}

export const usePermissionStore = defineStore("permission", () => {
  // asyncRoutes 路由菜单，构建动态路由 TODO接口问题,用的第三方的接口，接口返回的icon还是elementui的图标，导致菜单图标不能正常显示，所有这里只设置静态路由表,后面会后端了再搞
  const asyncRoutes = ref<RouteRecordRaw[]>([...constantRoutes]);

  // btnPermissions 页面按钮权限
  const btnPermissions = ref<string[]>([]);

  // 设置路由
  function setRoutes(routes: RouteRecordRaw[]) {
    // 静态路径+ 动态路由，
    // asyncRoutes.value = routes;
  }

  // 获取路由
  function generateRoutes() {
    return new Promise(async (resolve, reject) => {
      getInitMenus()
        .then(({ permissionList }) => {
          const routes = filterAsyncRoutes(permissionList);
          console.log("asyncRoutes", routes);
          setRoutes(routes);
          resolve(routes);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  return { asyncRoutes, btnPermissions, generateRoutes };
});

// 非setup
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
